package com.linkwechat.framework.config;



import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;

import com.github.pagehelper.PageInterceptor;
import com.linkwechat.common.tenant.TenantContextHolder;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * Mybatis支持*匹配扫描包
 *
 * @author ruoyi
 */
@Configuration
public class MyBatisPlusConfig
{


	/**
	 * 租户拦截器
	 */
	@Bean
	public TenantLineInnerInterceptor tenantLineInnerInterceptor() {
		return new TenantLineInnerInterceptor(new TenantLineHandler() {
			@Override
			public Expression getTenantId() {
				String tenantCode=TenantContextHolder.getTenantCode();
				// 启动时读取sys_config的配置，默认为0
				if(tenantCode==null){
					return new StringValue("0");
				}
				return new StringValue(tenantCode);
			}

			@Override
			public boolean ignoreTable(String tableName) {

				// 是否需要需要忽略某一张表
				List<String> tableNameList = new ArrayList<>(Arrays.asList(
					"sys_menu","sys_role_menu","sys_user_role","sys_role","sys_dict_type","sys_dict_data" // 公共功能相关表
					,"tables","columns","character_sets")); // 数据库的库的数据字典表
				String tenantCode=TenantContextHolder.getTenantCode();
				// 启动时读取sys_config的配置，默认为0
				if(tenantCode==null){
					tenantCode="0";
				}
				if(tenantCode.equals("0")){
					tableNameList.add("sys_user");
					tableNameList.add("sys_tenant");
					tableNameList.add("sys_role");
					tableNameList.add("sys_user_role");
				}

				if (tableNameList.contains(tableName)){
					return true;
				}

				return false;
			}

			@Override
			public String getTenantIdColumn() {
				return "tenant_code";
			}
		});
	}


    @Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor(TenantLineInnerInterceptor tenantLineInnerInterceptor){
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
		// 配置租户拦截器
		interceptor.addInnerInterceptor(tenantLineInnerInterceptor);
		return interceptor;
	}

	//pagehelper 分页配置
	@Bean
	ConfigurationCustomizer mybatisConfigurationCustomizer() {
		return new ConfigurationCustomizer() {
			@Override
			public void customize(MybatisConfiguration configuration) {
				configuration.addInterceptor(new com.github.pagehelper.PageInterceptor());
			}
		};
	}



}
